<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>JavaScript 数组排序 </title>
</head>
<body>
<h2>排序对象数组</h2>
<p>通过比较函数来对比属性值来对对象进行排序</p>

<p>点击按钮按年份对汽车进行排序：</p>

<button onclick="myFunction()">排序</button>

<p id="demo"></p>

<script>
  var cars = [
    {type:"BMW", year:2017},
    {type:"Audi", year:2019},
    {type:"porsche", year:2018}
  ];

  displayCars();

  function myFunction() {
    cars.sort(function(a, b){return a.year - b.year});
    displayCars();
  }

  function displayCars() {
    document.getElementById("demo").innerHTML =
            cars[0].type + " " + cars[0].year + "<br>" +
            cars[1].type + " " + cars[1].year + "<br>" +
            cars[2].type + " " + cars[2].year;
  }
</script>
</body>
</html>

<!--
语法：
cars.sort(function(a, b){return a.year - b.year});
-->


<!--
BMW 2017
porsche 2018
Audi 2019
-->